#include "person.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct _Persons
{
    int length;
    Person data[MAX_PERSONS_LENGTH];
} Persons;

Persons *ALL_PERSONS = NULL;
void Persons_Init()
{
    if (ALL_PERSONS != NULL)
    {
        return;
    }
    ALL_PERSONS = malloc(sizeof(Persons));
    memset(ALL_PERSONS, 0, sizeof(Persons));
}

uint8_t Person_Create(uint8_t age, char *name)
{
    if (ALL_PERSONS->length >= MAX_PERSONS_LENGTH)
    {
        return 255;
    }
    Person *self = &ALL_PERSONS->data[ALL_PERSONS->length++];
    self->age = age;
    snprintf(self->name, MAX_NAME_LENGTH, "%s", name);
    return ALL_PERSONS->length-1;
}

u_int8_t GetPerson(uint8_t id, Person *result){
    if (id >= MAX_PERSONS_LENGTH)
    {
        return 255;
    }
    Person *target = &(ALL_PERSONS->data[id]); 
    result->age = target->age;
    snprintf(result->name, MAX_NAME_LENGTH, "%s", target->name);
    return ALL_PERSONS->length-1;

}


uint8_t Person_Introduce(uint8_t id, char *introduce)
{
    if (id >= MAX_PERSONS_LENGTH)
    {
        return 255;
    }
    Person *person = &(ALL_PERSONS->data[id]);

    snprintf(introduce, MAX_INTRODUCE_LENGTH, "My name is %s. I am %d years old.", person->name, person->age);
    return FUNCTION_SUCCESS_CODE;
}
